package com.flyone.herbal.controller;

import cn.hutool.core.io.FileUtil;
import com.flyone.herbal.common.BaseResponse;
import com.flyone.herbal.common.ErrorCode;
import com.flyone.herbal.common.ResultUtils;
import com.flyone.herbal.model.dto.file.UploadFileRequest;
import com.flyone.herbal.model.entity.User;
import com.flyone.herbal.model.enums.FileUploadBizEnum;
import com.flyone.herbal.constant.FileConstant;
import com.flyone.herbal.exception.BusinessException;
import com.flyone.herbal.service.UserService;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.flyone.herbal.utils.QiniuUtils;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件接口
 */
@RestController
@RequestMapping("/file")
@Slf4j
@Api(tags = "文件接口")
public class FileController {

    @Resource
    private UserService userService;

    @Resource
    private QiniuUtils qiniuUtils;

    /**
     * 文件上传
     *
     * @param multipartFiles 文件
     * @param uploadFileRequest 上传文件请求
     * @param request 请求
     * @return 文件地址
     */
    @PostMapping("/upload")
    public BaseResponse<List<String>> uploadFile(@RequestPart("file") List<MultipartFile> multipartFiles,
                                                 UploadFileRequest uploadFileRequest, HttpServletRequest request) {
        List<String> urls = new ArrayList<>();
        if (multipartFiles.isEmpty()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        for (MultipartFile multipartFile : multipartFiles) {
            String biz = uploadFileRequest.getBiz();
            FileUploadBizEnum fileUploadBizEnum = FileUploadBizEnum.getEnumByValue(biz);
            if (fileUploadBizEnum == null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR);
            }
            validFile(multipartFile, fileUploadBizEnum);
            User loginUser = userService.getLoginUser(request);
            // 文件目录：根据业务、用户来划分
            String uuid = RandomStringUtils.randomAlphanumeric(8);
            String filename = uuid + "-" + multipartFile.getOriginalFilename();
            String filepath = String.format("/%s/%s/%s", fileUploadBizEnum.getValue(), loginUser.getId(), filename);
            try {
                // 上传文件
                boolean result = qiniuUtils.upload(multipartFile, filename);
                if (result) {
                    // 返回可访问地址
                    urls.add(FileConstant.QINIU_HOST + filename);
                }else {
                    throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
                }
            } catch (Exception e) {
                log.error("file upload error, filepath = " + filepath, e);
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
            }
        }
        return ResultUtils.success(urls);
    }

    /**
     * 校验文件
     *
     * @param multipartFile
     * @param fileUploadBizEnum 业务类型
     */
    private void validFile(MultipartFile multipartFile, FileUploadBizEnum fileUploadBizEnum) {
        // 文件大小
        long fileSize = multipartFile.getSize();
        // 文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        final long ONE_M = 1024 * 1024L;
        if (FileUploadBizEnum.USER_AVATAR.equals(fileUploadBizEnum)) {
            if (fileSize > ONE_M) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小不能超过 1M");
            }
            if (!Arrays.asList("jpeg", "jpg", "svg", "png", "webp").contains(fileSuffix)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件类型错误");
            }
        }
    }
}
